const { think } = require('thinkjs');
const Base = require('./base.js');
const moment = require('moment');
const BigNumber = require('bignumber.js');
const qiniu = require('qiniu');
const fs = require('fs');

module.exports = class extends Base {
  async detailAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 10;
    const query = this.get();

    delete query.page;
    delete query.size;

    if (query.id) {
      query['a.company_id'] = query.id;
      delete query.id;
    } else {
      query['a.company_id'] = this.getLoginCompanyId();
    }

    query['a.status'] = 0;

    const data = await this.model('product_detail')
      .alias('a')
      .join({
        product_list: {
          join: 'left',
          as: 'p',
          on: ['product_id', 'id'],
        },
      })
      .where(query)
      .field('p.name, p.product_unit, p.product_type, p.pruduct_standards, a.*')
      .order(['id DESC'])
      .page(page, size)
      .countSelect();
    return this.success(data);
  }
  async addDetailApplyAction() {
    const value = this.post();
    value.product_id = value.id;
    delete value.id;
    value.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
    value.create_month = moment().format('YYYY-MM');
    value.sale_id = this.getLoginCompanyId();
    const saleUser = await this.model('user_list')
      .where({ id: this.getLoginCompanyId() })
      .find();
    value.vendor_name = saleUser.company;
    value.vendor_phone = saleUser.mobile;
    value.vendor_addr = saleUser.addr;
    value.status = 0;
    value.type = 2;
    await this.model('product_detail').add(value);
    return this.success();
  }
  async auditApplyAction() {
    const status = this.post('status');
    const ids = this.post('id');
    let index = 0;
    for (const item of ids) {
      const detail = await this.model('product_detail')
        .where({ id: item, company_id: this.getLoginCompanyId() })
        .find();
      if (think.isEmpty(detail)) {
        index = 1;
        continue;
      }
      if (status === 2) {
        await this.model('product_detail').where({ id: item }).update({
          status: 3,
        });
      } else {
        const productDetail = await this.model('product_list')
          .where({ id: detail.product_id })
          .find();
        const oldUser = await this.model('user_list')
          .where({ id: detail.company_id })
          .find();

        if (BigNumber(productDetail.num).lt(BigNumber(detail.num))) {
          index = 2;
          continue;
        }
        const newNum = BigNumber(productDetail.num)
          .minus(BigNumber(detail.num))
          .toString();

        await this.model('product_detail').where({ id: item }).update({
          status: 1,
        });
        await this.model('product_list')
          .where({ id: detail.product_id })
          .update({
            num: newNum,
          });

        const hasData = await this.model('product_list')
          .where({
            name: productDetail.name,
            product_type: productDetail.product_type,
            product_unit: productDetail.product_unit,
            batch: productDetail.batch,
            opt_time: productDetail.opt_time,
            company_id: detail.sale_id,
          })
          .find();

        if (!think.isEmpty(hasData)) {
          hasData.product_id = hasData.id;
          delete hasData.id;
          delete hasData.drivers;
          hasData.create_month = moment().format('YYYY-MM');
          hasData.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
          hasData.create_month = moment().format('YYYY-MM');
          hasData.company_id = detail.sale_id;
          hasData.status = 1;
          hasData.numOld = hasData.num;
          hasData.num = detail.num;
          hasData.vendor_name = oldUser.company;
          hasData.vendor_phone = oldUser.mobile;
          hasData.vendor_addr = oldUser.addr;

          const newNum = BigNumber(hasData.numOld)
            .plus(BigNumber(detail.num))
            .toString();
          await this.model('product_detail').add(hasData);
          await this.model('product_list')
            .where({ id: hasData.product_id })
            .update({
              num: newNum,
            });
        } else {
          delete productDetail.id;
          delete productDetail.staff;
          delete productDetail.drivers;
          delete productDetail.qrcode;
          productDetail.company_id = detail.sale_id;
          productDetail.num = detail.num;

          const d = await this.model('product_list').add(productDetail);

          const WeixinServe = this.service('weixin', 'api');
          const img = await WeixinServe.getWxcode(d);

          var accessKey = think.config('qiniu.accessKey');
          var secretKey = think.config('qiniu.secretKey');
          var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
          var options = {
            scope: think.config('qiniu.scope'),
            returnBody:
              '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
            returnBodyType: 'application/json',
          };
          var putPolicy = new qiniu.rs.PutPolicy(options);
          var uploadToken = putPolicy.uploadToken(mac);

          const config = new qiniu.conf.Config();
          config.zone = qiniu.zone.Zone_z0;

          var fileName = Date.now() + '.png';
          // 构建图片路径
          var filePath = './www/images/' + fileName;
          // 过滤data:URL
          var base64Data = img.replace(/^data:image\/\w+;base64,/, '');
          var dataBuffer = Buffer.from(base64Data, 'base64');
          fs.writeFile(filePath, dataBuffer, (err) => {
            if (err) {
              console.log('文件写入失败');
            } else {
              var localFile = filePath;
              var formUploader = new qiniu.form_up.FormUploader(config);
              var putExtra = new qiniu.form_up.PutExtra();
              var key = fileName;

              // 文件上传
              formUploader.putFile(
                uploadToken,
                key,
                localFile,
                putExtra,
                async (respErr, respBody, respInfo) => {
                  if (respErr) {
                    console.log('上传失败');
                  }
                  if (respInfo.statusCode === 200) {
                    var imageSrc = respBody.key;
                    this.model('product_list')
                      .where({ id: d })
                      .update({
                        qrcode: think.config('qiniu.url') + imageSrc,
                      });
                  } else {
                  }
                  // 上传之后删除本地文件
                  fs.unlinkSync(filePath);
                }
              );
            }
          });
          detail.company_id = detail.sale_id;
          detail.product_id = d;
          detail.type = 0;
          detail.status = 1;
          delete detail.staff;
          delete detail.id;
          delete detail.drivers;
          detail.create_month = moment().format('YYYY-MM');
          detail.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
          detail.vendor_name = oldUser.company;
          detail.vendor_phone = oldUser.mobile;
          detail.vendor_addr = oldUser.addr;
          await this.model('product_detail').add(detail);
          this.model('user_list')
            .where({ id: this.getLoginCompanyId() })
            .update({
              update_time: new Date().getTime(),
            });
        }

        this.model('user_list')
          .where({ id: ['IN', [this.getLoginCompanyId(), detail.sale_id]] })
          .update({
            update_time: new Date().getTime(),
          });
      }
    }
    if (index === 0) {
      return this.success();
    } else {
      return this.fail(index);
    }
  }
};
